using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.VisualStudio.DebuggerVisualizers;
using Microsoft.SharePoint;
using System.Data;

namespace SPDV
{
    public class SPRoleAssignmentObjectProvider : VisualizerObjectSource
    {
        public override void GetData(object target, System.IO.Stream outgoingData)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            if(target is SPRoleAssignmentCollection)
                formatter.Serialize(outgoingData, GetSerializableObject((SPRoleAssignmentCollection)target));
            else
                if (target is SPList)
                    formatter.Serialize(outgoingData, GetSerializableObject((SPList)target));
        }
        private SPRoleAssignmentData GetSerializableObject(SPRoleAssignmentCollection RoleAssignments)
        {
            SPRoleAssignmentData rad = new SPRoleAssignmentData();
            SPList l = RoleAssignments.Parent as SPList;
            if (null != l)
            {
                rad.ID = l.ID;
                rad.Title = l.Title;
            }
            SPListItem i = RoleAssignments.Parent as SPListItem;
            if (null != i)
            {
                rad.ID = i.ParentList.ID;
                rad.Title = i.ParentList.Title;
                rad.ItemID = i.ID;
            }
            foreach (SPRoleAssignment role in RoleAssignments)
            {
                SPUser u = role.Member as SPUser;
                if (null != u)
                {
                    SPUserData ud = new SPUserData();
                    ud.LoginName = u.LoginName;
                    ud.Name = u.Name;
                    ud.Email = u.Email;
                    rad.users.Add(ud);
                }
                else
                {
                    SPGroup g = role.Member as SPGroup;
                    if (null != g)
                    {
                        SPGroupData gd = new SPGroupData();
                        gd.Description = g.Description;
                        gd.Name = g.Name;
                        rad.groups.Add(gd);
                    }
                }
            }
            return rad;
        }
        private SPRoleAssignmentData GetSerializableObject(SPList list)
        {
            return GetSerializableObject(list.RoleAssignments);
        }
    }
}